
/**
** \file       if.c
**
** \brief      this function parse the if rule
**
** \authors    Ben M'rad Hanna, Boillot Ulysse, De Olivera Guillaume
**             Laterem Hamza and Nguyen Viet Dung
**
** \version    0.8
**
** \date       26 November 2010
**
*/

#include "rules.h"

static s_ruleif      *rule_if1(s_ruleif       *rif)
{
  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
    return (NULL);

  rif->in_if = calloc(1, sizeof (s_cmpdlist));

  if (g_data->lexer == NULL || rule_compound_list(rif->in_if) == NULL)
  {
    free(rif->in_if);
    rif->in_if = NULL;
    return (NULL);
  }

  return (rif);
}

static s_ruleif      *rule_if2(s_ruleif       *rif)
{
  g_data->lexer = g_data->lexer->next;

  if (g_data->lexer == NULL)
    return (NULL);

  rif->in_then = calloc(1, sizeof (s_cmpdlist));

  if (rule_compound_list(rif->in_then) == NULL)
  {
    free(rif->in_then);
    rif->in_then = NULL;
    return (NULL);
  }

  return (rif);
}

static s_ruleif         *my_free(s_ruleif       *rif)
{
  free_ruleif(rif);
  rif = NULL;

  return (NULL);
}

s_ruleif             *rule_if(s_ruleif        *rif)
{
  if (g_data->lexer != NULL && strcmp(g_data->lexer->token->id, "if") == 0)
  {
    if (rule_if1(rif) == NULL)
      return (NULL);
    if (strcmp(g_data->lexer->token->id, "then") != 0)
      return (NULL);
    if (rule_if2(rif) == NULL)
      return (NULL);

    if (g_data->lexer == NULL)
      return (NULL);

    rif->else_clause = calloc(1, sizeof (s_else_clause));

    if (g_data->lexer == NULL || rule_else_clause(rif->else_clause) == NULL)
    {
      free(rif->else_clause);
      rif->else_clause = NULL;
      return (rif);
    }

    if (strcmp(g_data->lexer->token->id, "fi") != 0)
      return (my_free(rif));

    g_data->lexer = g_data->lexer->next;
    return (rif);
  }

  return (NULL);
}
